package main

import (
	"context"
	"log"
	"server/rental/ai"
	rentalpb "server/rental/api/gen/v1"
	"server/rental/dao"
	"server/rental/trip"
	"server/rental/trip/client/car"
	"server/rental/trip/client/poi"
	"server/rental/trip/client/profile"
	coolenvpb "server/shared/coolenv"
	"server/shared/server"

	"google.golang.org/grpc/credentials/insecure"

	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"

	"go.uber.org/zap"
	"google.golang.org/grpc"
)

func main() {
	logger, err := server.NewZapLogger()
	if err != nil {
		log.Fatalf("cannot create logger %v\n", err)
	}
	c := context.Background()
	mongoClient, err := mongo.Connect(c, options.Client().ApplyURI("mongodb://192.168.182.141:27017/?readPreference=primary&ssl=false"))
	if err != nil {
		logger.Fatal("cannot connect mongodb", zap.Error(err))
	}
	conn, err := grpc.Dial("192.168.182.141:18001", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		logger.Fatal("cannot connect ai server", zap.Error(err))
	}
	AIClient := coolenvpb.NewAIServiceClient(conn)
	err = server.RunGRPCServer(&server.GRPCConfig{
		Name:              "TripService",
		Addr:              ":8082",
		AuthPublicKeyFile: "../shared/auth/public.key",
		Logger:            logger,
		RegisterFunc: func(server *grpc.Server) {
			rentalpb.RegisterTripServiceServer(server, &trip.Service{
				Logger:                         logger,
				CarManager:                     &car.Manager{},
				ProfileManager:                 &profile.Manager{},
				POIManager:                     &poi.Manager{},
				DistanceCalc:                   &ai.Client{AIClient: AIClient},
				Mongo:                          dao.NewMongo(mongoClient.Database("coolcar")),
				UnimplementedTripServiceServer: &rentalpb.UnimplementedTripServiceServer{},
			})
		},
	})
	if err != nil {
		logger.Fatal("server serve failed", zap.Error(err))
	}
}
